//
//  HJCHomeTableViewController.swift
//  新浪微博Swift
//
//  Created by 郝俊聪 on 15/5/10.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit

class HJCHomeTableViewController: HJCBaseTableViewController {
    

    //定义行高缓存
    var rowHeightCache : NSCache = NSCache()
    //记录是否转场
    var isPersent =  false
    //转场的页面
    var persentedDummyView : UIView?
    
    //记录转场视图所在的homecell
    weak var cell : HJCHomeCell?

    //定义装有微博信息的数组
    var statuses : [HJCStatus]?{
        didSet{
//            刷新数据
//            println(self.statuses?.count)
            tableView.reloadData()
            //结束刷新
            self.refreshControl?.endRefreshing()
            println(statuses?.count)
        }
    }
    
   
    @IBOutlet weak var titleBtn: HJCHomeTitleButton!
    
    @IBAction func clickTitleBtn() {
        
        //旋转图片

        
    }
    
    @IBAction func pullRefreshControl() {
        //
        self.refreshControl?.beginRefreshing()
        //刷新数据
        loadStatuses()
        
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()

        //设置按钮
        setTitleBtn()
        if userLogin{
            //初始化用户数据
            pullRefreshControl()
        }
        
    }
    //定义一个上拉刷新的标记
    var isPullUpFlag = false
    ///初始化用户数据的方法
    func loadStatuses(){
        var since_id : Int = 0
        since_id = statuses?.first?.id ?? 0
        var max_id : Int = 0
        if isPullUpFlag {
           since_id = 0
           max_id = statuses?.last?.id ?? 0
        }
        HJCStatus.loadStatuses(since_id, max_id:max_id ) { (statuses) -> () in
            
            if statuses == nil{
//               println("数据出错")
               self.refreshControl?.endRefreshing()
               return
            }
            
            //赋值
            if  statuses!.count == 0{
//                println("没有数据")
                self.refreshControl?.endRefreshing()
                //显示提示动画
                self.showTipView(0)
                return
            }else if since_id > 0{
//                println("下拉数据")
//                println(statuses)
                self.statuses! = statuses! + self.statuses!
                //显示图示动画
                self.showTipView(statuses!.count)
            }else if max_id > 0{
                //标记为不是上拉刷新
//                println("上拉数据")
                self.statuses! += statuses!
                self.isPullUpFlag = false
            }else{
//                println("新数据")
                self.statuses = statuses
            }

        }
    }
    
    func showTipView(count:Int){
        var text = count == 0 ? "没有新微博" : "\(count)"+"新微博"
        (navigationController?.navigationBar as! HJCHomeNavigationBar).tipLabelAnimation(text)
    }
    
    //设置标题按钮
    func setTitleBtn(){
        if sharedaccount != nil{
            //登录了
            titleBtn.setTitle(sharedaccount!.name ?? " " + " ", forState: UIControlState.Normal)
        }else{
            //没登录，不设置图片
            titleBtn.setImage(nil,forState: UIControlState.Normal)
        }
    }
    

    //设置未登录时候页面属性
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        visitorView?.setViewInfo("visitordiscover_feed_image_house", rollingName: "visitordiscover_feed_image_smallicon", message: "关注一些人,回这里看看有惊喜", isHome: true)
        }
    
    let poperDelegate = HJCPopoverAnimator()
    
    //获得跳转的目标控制器
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        //取得目标控制器
        if segue.identifier == "home2Popover"{
            let poperVC = segue.destinationViewController as! HJCPopViewController
            
            //设置转场代理
            poperVC.transitioningDelegate = poperDelegate
            
            //设置演示控制器的尺寸
            let w = 200.0 as CGFloat
            let h = 250.0 as CGFloat
            let x = (self.view.frame.size.width - w)*0.5
            let y = 64 as CGFloat

            poperDelegate.presentedFrame = CGRectMake(x, y , w, h)
            
          //设置目标控制器的展现方式
            poperVC.modalPresentationStyle = UIModalPresentationStyle.Custom
            
        }
        
    }
   
    ///点击二维码按钮
    @IBAction func clickQRCodeItem() {
        
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        let vc = sb.instantiateInitialViewController() as! UIViewController
        //跳转
        presentViewController(vc, animated: true) { () -> Void in
            
        }
    }
}

extension HJCHomeTableViewController {
    
    //MARK: - UITableViewDataSource
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //取得数据
        let status = statuses![indexPath.row]
        //获得cell的identifier
        let id = HJCHomeCell.identifierOfcell(status)
        //获得可重用的cell
        let cell = tableView.dequeueReusableCellWithIdentifier(id) as! HJCHomeCell
        //赋值
        cell.status = status
        //设置代理
        cell.photoDelegate = self
        
        //当是最后一行的时候，显示
        if (indexPath.row == statuses!.count - 1) && !isPullUpFlag{
           //标记为要上拉刷新数据
            isPullUpFlag = true
            //刷新数据
            loadStatuses()
        
        }
        

        //返回
        return cell
    }
    
    //MARK: - UITableViewDelegate
    //预估行高
    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return 200
    }
    
    //准确行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        if statuses?.count == 0 {
           return 0
        }
        //取得数据
        let status = statuses![indexPath.row]
        
        //先从行高缓存中取
        if  let rowHeight = rowHeightCache.objectForKey(status.id) as? CGFloat{
             return rowHeight
        }
        
        //获得identifier
        let id = HJCHomeCell.identifierOfcell(status)
        
        //取出合适的cell
        let cell = tableView.dequeueReusableCellWithIdentifier(id)  as! HJCHomeCell
        //计算出行高
        let rowHeigth = cell.heightForCell(status)
        
        //缓存起来，下次直接取
        rowHeightCache.setObject(rowHeigth, forKey: status.id)
        return rowHeigth
    }
    
    
    

}

extension HJCHomeTableViewController : HJCHomeCellDelegate{
    func homeCellDidClickPhoto(cell: HJCHomeCell, index: Int) {
        
        //创建照片浏览器控制器
        let photoBrowser = HJCPhotoBrowserViewController()
        
        //传值
        photoBrowser.largeImageURLStr = cell.status?.weiboLargePic_urls
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        photoBrowser.selectedIndex = indexPath
        //记录cell
        self.cell = cell
        //设置Model转场代理
        photoBrowser.transitioningDelegate = self
        //设置Model类型
        photoBrowser.modalPresentationStyle = UIModalPresentationStyle.Custom
        let pictureItem = cell.pictureView.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0))
        persentedDummyView = pictureItem?.snapshotViewAfterScreenUpdates(true)
        //算出目前tableview的偏移量
        let offsetY = self.tableView.contentOffset.y
        //设置persentedDummyView相对于根View的frame
       
        let persentedDummyViewY = cell.frame.origin.y - self.tableView.contentOffset.y + cell.pictureView.frame.origin.y + pictureItem!.frame.origin.y
        let persentedDummyViewX = cell.pictureView.frame.origin.x + pictureItem!.frame.origin.x
        persentedDummyView?.frame = CGRectMake(persentedDummyViewX, persentedDummyViewY, pictureItem!.frame.size.width, pictureItem!.frame.size.height)

        //跳转
        presentViewController(photoBrowser, animated: true) { () -> Void in

        }
        
    }
    

}

///转场代理
extension HJCHomeTableViewController:UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning{
    ///MARK：- UIViewControllerTransitioningDelegate
    //谁负责转场
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{
        
        isPersent = true
        return self
    }
//    谁负责解除转场
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPersent = false
        return self
    }
    
     ///MARK：- UIViewControllerAnimatedTransitioning
    //转场时间
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval{
        return 0.5
    }
    
    //转场上下文
    func animateTransition(transitionContext: UIViewControllerContextTransitioning){
        
        //转场动画
        if isPersent{
            if let toView = transitionContext.viewForKey(UITransitionContextToViewKey){
                //将傀儡视图加入containerView()
               transitionContext.containerView().addSubview(self.persentedDummyView!)

                UIView.animateWithDuration(0.5, animations: { () -> Void in
                     self.persentedDummyView?.frame = transitionContext.containerView().frame
                    toView.frame = UIScreen.mainScreen().bounds
                }, completion: { (_) -> Void in
                    //移除傀儡视图
                     self.persentedDummyView?.removeFromSuperview()
                    //加入要正常显示的视图
                    transitionContext.containerView().addSubview(toView)
                    //结束
                    transitionContext.completeTransition(true)
                })
            }
        }
        //退场动画
        if !isPersent{
            if let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey){
                
                //隐藏目标控制器
                let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! HJCPhotoBrowserViewController
                fromVC.view.hidden = true
               //获得fromVC的快照
                let dummy = (fromVC.collectionView.visibleCells().last!).snapshotViewAfterScreenUpdates(false)
                
                //获得正在查看的cell的index
               let indexPath = fromVC.collectionView.indexPathForCell(fromVC.collectionView.visibleCells().last! as! UICollectionViewCell)
                //获得哪一张cell
                let pictureItem = cell!.pictureView.cellForItemAtIndexPath(indexPath!)
                let offsetY = self.tableView.contentOffset.y
                //设置dummy相对于根View的frame
                let y = cell!.frame.origin.y - self.tableView.contentOffset.y + cell!.pictureView.frame.origin.y + pictureItem!.frame.origin.y
                let x = cell!.pictureView.frame.origin.x + pictureItem!.frame.origin.x
                let rect = CGRectMake(x, y, pictureItem!.frame.size.width, pictureItem!.frame.size.height)

                //将傀儡视图放入containerView
                transitionContext.containerView().addSubview(dummy)
                //执行动画
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                       dummy.frame = rect
                       dummy.alpha = 0
                    }, completion: { (_) -> Void in
                        //移除傀儡视图
                        dummy.removeFromSuperview()
                        //结束
                        transitionContext.completeTransition(true)
                })
            }
        }
    }
    
    
}
